/**
 * Copyright (c) 2009 Netflix-Flex_API Contributors.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of 
 * this software and associated documentation files (the "Software"), to deal in 
 * the Software without restriction, including without limitation the rights to 
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 
 * of the Software, and to permit persons to whom the Software is furnished to do 
 * so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all 
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE. 
 * */
package com.netflix.webapis.catalog
{
	import com.netflix.webapis.ParamsBase;
	import com.netflix.webapis.ServiceBase;
	import com.netflix.webapis.ServiceFault;
	import com.netflix.webapis.catalog.params.CatalogParams;
	import com.netflix.webapis.catalog.vo.CatalogTitleVO;
	import com.netflix.webapis.events.NetflixFaultEvent;
	import com.netflix.webapis.events.NetflixResultEvent;
	import com.netflix.webapis.xml.NetflixXMLUtil;
	
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	import org.iotashan.oauth.OAuthRequest;
	
	/**
	 * Catalog Services under the <i>People</i> category.
	 * @author jonbcampos
	 * 
	 */	
	public class PeopleService extends ServiceBase
	{
		public static const PEOPLE_SERVICE:String = "people";
		public static const PERSON_SERVICE:String = "person"; 
		public static const FILMOGRAPHY_SERVICE:String = "filmography"; 
		
		protected static const PEOPLE_URL:String = NETFLIX_BASE_URL+"catalog/people";
		protected static const FILMOGRAPHY_PART:String = "filmography";

		public function PeopleService()
		{
		}

		//----------------------------
		//
		// Public Variables
		//
		//----------------------------
		[Bindable]
		[Inspectable(enumeration="people,person",defaultValue="people")]
		public var type:String = PEOPLE_SERVICE;
		
		/**
		 * @inherit
		 */
		override public function send(parameters:ParamsBase=null):void
		{
			super.send(parameters);
			
			switch(type)
			{
				case PEOPLE_SERVICE:
					peopleService(parameters);
				break;
				case PERSON_SERVICE:
					personService(parameters);
				break;
			}
		}
		
		/**
		 * Calls for the peopleService Service. 
		 * @param params
		 * 
		 */	
		public function peopleService(params:ParamsBase=null):void
		{
			handleServiceLoading(PEOPLE_URL,NetflixResultEvent.PEOPLE_SERVICE_RESULT,params);
		}
		
		/**
		 * Calls for the personService Service. 
		 * @param params
		 * 
		 */
		public function personService(params:ParamsBase=null):void
		{
			handleServiceLoading(PEOPLE_URL,NetflixResultEvent.PERSON_SERVICE_RESULT,params);
		}
		
		/**
		 * @inherit
		 */
		override protected function handleServiceLoading(methodString:String, dispatchType:String, params:ParamsBase = null):void
		{
			var sendQuery:String = methodString;
			var typeQuery:String;
			
			if(params != null)
			{
				switch(dispatchType)
				{
					case NetflixResultEvent.PEOPLE_SERVICE_RESULT:
						//
						// parse xml and create objects
						//
					break;
					case NetflixResultEvent.PERSON_SERVICE_RESULT:
						sendQuery += "/"+CatalogParams(params).personID;
					break;
					case NetflixResultEvent.FILMOGRAPHY_SERVICE_RESULT:
						sendQuery += "/"+CatalogParams(params).personID+"/"+FILMOGRAPHY_PART;
					break;
				}
			}
			var queryXMLService:HTTPService = new HTTPService();
			var tokenRequest:OAuthRequest = new OAuthRequest("GET",sendQuery,params.toObject(),consumer,accessToken);
			queryXMLService.url = tokenRequest.buildRequest(SIG_METHOD);
			trace(tokenRequest.buildRequest(SIG_METHOD));
			queryXMLService.method = "GET";
			queryXMLService.resultFormat = "e4x";
			queryXMLService.addEventListener(ResultEvent.RESULT,onCompleteHandler);
			queryXMLService.addEventListener(FaultEvent.FAULT,onFault);
			queryXMLService.send();
		
			function onCompleteHandler(event:ResultEvent):void
			{
				queryXMLService.removeEventListener(ResultEvent.RESULT,onCompleteHandler);
				var queryXML:XML = event.result as XML;
				
				if(queryXML.Error == undefined)
					formatAndDispatch(queryXML, dispatchType);
				else
					dispatchFault(new ServiceFault(NetflixFaultEvent.API_RESPONSE, queryXML.Error, queryXML.Error.Message));
			}
			
			function onFault(event:FaultEvent):void
			{
				queryXMLService.removeEventListener(FaultEvent.FAULT,onFault);
				dispatchFault(new ServiceFault(event.fault.faultCode,event.fault.faultString,event.fault.faultDetail));
			}
		}
		
		/**
		 * @inherit
		 */	
		override protected function formatAndDispatch(returnedXML:XML, dispatchType:String):void
		{
			if(increment == 0) lastResult = new Array();
			
			var len:int = lastResult.length;
			numberOfResults = returnedXML.number_of_results;
			startIndex = returnedXML.start_index;
			resultsPerPage = returnedXML.results_per_page;
			
			var resultsArray:Array = new Array();
			var resultNode:XML;
			
			//loop through child nodes and build value objects based on catagory type
			switch(dispatchType)
			{
				case NetflixResultEvent.PEOPLE_SERVICE_RESULT:
					for each(resultNode in returnedXML..person) {
						resultsArray.push(NetflixXMLUtil.handlePerson(resultNode));
					}
				break;
				case NetflixResultEvent.PERSON_SERVICE_RESULT:
					resultsArray.push(NetflixXMLUtil.handlePerson(returnedXML));
				break;
				case NetflixResultEvent.FILMOGRAPHY_SERVICE_RESULT:
					for each(resultNode in returnedXML..filmography_item){
						resultsArray.push(NetflixXMLUtil.handleCatalogTitleNode(resultNode, new CatalogTitleVO));
					}
			}
			dispatchResult(resultsArray,dispatchType);
		}
		
	}
}